package org.example.baidu_translation;

import com.google.gson.Gson;
import okhttp3.*;
import org.example.translation.*;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.Random;

public class BaiduTranslation extends DefaultLangSupportHandler {
    private final Random random = new Random();
    private final MessageDigest md5;
    private final String APPID = propValueSupplier.get("baidu.appId");
    private final String SECRET =propValueSupplier.get("baidu.secretKey");
    private final OkHttpClient client = new OkHttpClient();
    private final MediaType mediaType = MediaType.parse("application/json");
    private final Gson gson = new Gson();

    public BaiduTranslation(PropValueSupplier propValueSupplier) {
        super(propValueSupplier);
        translationApiType = TranslationApiType.Interval;

        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public TranslationResponseBean requestTranslation(TranslationPostBean postBean) {
        int salt = random.nextInt(20);
        String s1 = APPID + postBean.getSourceString() + salt + SECRET;
        FormBody.Builder builder = new FormBody.Builder();
        FormBody body = builder.add("q", postBean.getSourceString())
                .add("from", getSupportLang(postBean.getSourceCountry()))
                .add("to", getSupportLang(postBean.getTargetCountry()))
                .add("appid", APPID)
                .add("salt", salt + "")
                .add("sign",encryption(s1))
                .build();

        Request request = new Request.Builder()
                .url("https://fanyi-api.baidu.com/api/trans/vip/translate")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            String s2 = response.body().string();
            BaiduResponseBean baiduResponseBean = gson.fromJson(s2, BaiduResponseBean.class);
            if (baiduResponseBean == null || baiduResponseBean.getTransResult() == null) {
                RuntimeException runtimeException = new RuntimeException("server response:" + s2 +
                        "\nSourceCountry:" + postBean.getSourceCountry() +
                        "\nTargetCountry:" + postBean.getTargetCountry() +
                        "\nContent:" + postBean.getSourceString());
                runtimeException.printStackTrace();
                translation(postBean);
            } else {
                return new TranslationResponseBean()
                        .setTargetCountry(baiduResponseBean.getTo())
                        .setSourceCountry(baiduResponseBean.getFrom())
                        .setSourceString(baiduResponseBean.getTransResult().get(0).getSrc())
                        .setTargetResult(baiduResponseBean.getTransResult().get(0).getDst());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return null;
    }

    /**
     * md5加密 32位 小写
     * @param plainText
     * @return
     */
    public String encryption(String plainText) {
        String re_md5;
        md5.update(plainText.getBytes());
        byte b[] = md5.digest();

        int i;

        StringBuffer buf = new StringBuffer("");
        for (int offset = 0; offset < b.length; offset++) {
            i = b[offset];
            if (i < 0)
                i += 256;
            if (i < 16)
                buf.append("0");
            buf.append(Integer.toHexString(i));
        }

        re_md5 = buf.toString();

        return re_md5;
    }
}
